//
//  ContactSearch.m
//  Speedater
//
//  Created by Ngo Thang on 1/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ContactSearch.h"
#import "Start.h"
#import "ContactDetail.h"
#import "AppDelegate.h"
#import "MAnnotation.h"
#import "MKMapView+ZoomLevel.h"
#import "MapOverlay.h"
#import "MapOverlayView.h"
#import "asyncimageview.h"
#import "JSON.h"

#define ZOOM_LEVEL 14
#define degreesToRadians(x) (M_PI * (x) / 180.0)

@interface ContactSearch (private)

- (void)cleanup;

@end

@implementation ContactSearch (private)

- (void)cleanup 
{
    if (responseData != nil)
        responseData = nil;
    
    self.myTabBar = nil;
    self.myMKMapView = nil;
    self.myMapView = nil;
    self.locationArray = nil;
    self.listOfSections = nil;
    self.radarGScanImageView = nil;
    self.radarPsudoImageView = nil;
    self.radarWScanImageView = nil;
    self.friendUsername = nil;
    self.backArrowButton = nil;
    self.nextArrowButton = nil;
    self.myTableView = nil;
}

@end


@implementation ContactSearch

@synthesize myTabBar;
@synthesize myMKMapView;
@synthesize myMapView;
@synthesize locationArray, listOfSections;
@synthesize radarGScanImageView, radarPsudoImageView, radarWScanImageView;
@synthesize friendUsername;
@synthesize backArrowButton, nextArrowButton;
@synthesize myTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"CONTACTSEARCH -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

-(void)doScrollTo:(NSInteger)index
{
    NSIndexPath *indPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.myTableView scrollToRowAtIndexPath:indPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (IBAction)backArrowButtonClick:(id)sender
{
    NSInteger row = [[[myTableView indexPathsForVisibleRows] objectAtIndex:0] row];
    if (row-1 >= 0) row -= 1;
    [self doScrollTo:row];
}

- (IBAction)nextArrowButtonClick:(id)sender
{
    NSInteger row = [[[myTableView indexPathsForVisibleRows] objectAtIndex:0] row];
    NSInteger total = [myTableView numberOfRowsInSection:0];
    if (row+1 < total) row += 1;
    [self doScrollTo:row];
}

-(void)addOnGoogleMap
{
    radarPsudoImageView.hidden = TRUE;
    
    for (id annotation in myMKMapView.annotations) {
        if ([annotation isKindOfClass:[MAnnotation class]]){
            [myMKMapView removeAnnotation:annotation];
        }
    }
    
    CLLocationCoordinate2D l0 = CLLocationCoordinate2DMake(0.0, 0.0);
    
    for(NSDictionary *dict in locationArray){
        CLLocationCoordinate2D l;
        NSDictionary *location = [dict objectForKey:@"location"];
        
        l.latitude = [[location objectForKey:@"lat"] floatValue];
        l.longitude = [[location objectForKey:@"lon"] floatValue];
        
        NSString *username = [dict objectForKey:@"username"];
        NSString *myUsername = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
        
        if ([myUsername isEqualToString:username])
        {
            l0 = l;
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:YES] autorelease]];
            //NSLog(@"-> %@", username);
            
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"acoustic_signal"] && ([locationArray count]-1))
            {
                AppDelegate *d = [[UIApplication sharedApplication] delegate];
                if ([[dict objectForKey:@"suche"] intValue])
                    [d playTiger];
                else
                    [d playCat];
            }
        }
        else 
        {   if (!friendUsername)
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        else if ([friendUsername isEqualToString:username])
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        }
    }
    
    int radius = [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue];
    int zoom_level = (radius == 4500) ? 10 : ZOOM_LEVEL;
    [myMKMapView setCenterCoordinate:l0 zoomLevel:zoom_level animated:NO];
    
    MapOverlay *mapOverlayTemp = [[MapOverlay alloc] initWithType:1 andZoomLevel:zoom_level];
    mapOverlayTemp.coordinate = l0;
    [myMKMapView addOverlay:mapOverlayTemp];
    [mapOverlayTemp release];
    if (mapOverlay)
    {
        [myMKMapView removeOverlay:mapOverlay];
        mapOverlay = nil;
    }
    mapOverlay = mapOverlayTemp;
}

- (void)onRadarGScanning
{
    if (gRadian == 360) gRadian = 1;
    radarGScanImageView.transform = CGAffineTransformMakeRotation(degreesToRadians(gRadian));
    gRadian += 1;
}

-(void)onUpdateRadarLocation
{
    radarGScanImageView.hidden = YES;
    radarWScanImageView.hidden = YES;
    [timer1 invalidate];
    timer1 = nil;
    
    // loading
    [HUD hide:YES];
}

- (void)findNewFriends
{
    nextArrowButton.enabled = NO;
    backArrowButton.enabled = NO;
    
    radarWScanImageView.hidden = NO;
    radarGScanImageView.hidden = NO;
    timer1 = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onRadarGScanning) userInfo:nil repeats:YES];
    
    AppDelegate *d = [[UIApplication sharedApplication] delegate];
    
    //NSLog(@"GPS(%f, %f)", d.lat, d.lon);
    
    NSString *postString = [NSString stringWithFormat:@"op=findfriend&username=%@&radius=%d&lat=%f&lon=%f",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue], d.lat, d.lon];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        HUD.alpha = 0.02;
        [HUD show:YES];
    }
    [conn release];
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"CONTACTSEARCH -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"CONTACTSEARCH -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"Merkliste";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    
    // init data
    locationArray = [[NSMutableArray alloc] init];
    listOfSections = [[NSMutableArray alloc] init];
    
}

- (void)viewDidUnload
{
    //NSLog(@"CONTACTSEARCH -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"CONTACTSEARCH -> viewWillAppear");
    //NSLog(@"CONTACTSEARCH -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:2 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
    
    // find new friends
    [self findNewFriends];
} 

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma -
#pragma - TableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [listOfSections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[listOfSections objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];        
    }
    else 
    {
        [[cell viewWithTag:999] removeFromSuperview];
        [[cell viewWithTag:998] removeFromSuperview];
        [[cell viewWithTag:997] removeFromSuperview];
        [[cell viewWithTag:996] removeFromSuperview];
    }
    // Configure the cell.
    NSMutableArray *sectionFields = [listOfSections objectAtIndex:[indexPath section]];
    NSDictionary *dicField = [sectionFields objectAtIndex:[indexPath row]];
    
    AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(10, 15, 55, 55)];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], [dicField objectForKey:@"username"]]];
	[asyncImage loadImageFromURL:avatarURL];
    [cell addSubview:asyncImage];
    [asyncImage release];
    
    UILabel *nameView =[[UILabel alloc] initWithFrame:CGRectMake(80, 20, 230, 30)];
    nameView.tag = 998;
    [nameView setBackgroundColor:[UIColor clearColor]];
    [nameView setFont:[UIFont boldSystemFontOfSize:16]];
    [nameView setText:[dicField objectForKey:@"username"]];
    [cell addSubview:nameView];
    [nameView release];
    
    UILabel *locationView = [[UILabel alloc] initWithFrame:CGRectMake(80, 38, 230, 30)];
    locationView.tag = 997;
    [locationView setFont:[UIFont boldSystemFontOfSize:13]];
    [locationView setTextColor:[UIColor darkGrayColor]];
    [locationView setBackgroundColor:[UIColor clearColor]];
    [locationView setText:[NSString stringWithFormat:@"%@ meter entfernt", [dicField objectForKey:@"distance"]]];
    [cell addSubview:locationView];
    [locationView release];
    
    UIImageView *lightView =[[UIImageView alloc] initWithFrame:CGRectMake(235, 20, 45, 45)];
    lightView.tag = 996;
    switch ([[dicField objectForKey:@"ampel"] integerValue]) {
        case 0:
            [lightView setImage:[UIImage imageNamed:@"one_light_red.png"]];
            break;
        case 1:
            [lightView setImage:[UIImage imageNamed:@"one_light_yellow.png"]];
            break;
        case 2:
            [lightView setImage:[UIImage imageNamed:@"one_light_green.png"]];
            break;
        default:
            break;
    }
    [cell addSubview:lightView];
    [lightView release];
    
    cell.textLabel.text = [dicField objectForKey:@"label"];
    [cell setBackgroundColor:[UIColor colorWithRed:((float) 235 / 255.0f) green:((float) 236 / 255.0f) blue:((float) 240 / 255.0f) alpha:0.45f]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sectionFields = [listOfSections objectAtIndex:[indexPath section]];
    NSDictionary *dicField = [sectionFields objectAtIndex:[indexPath row]];
    
    ContactDetail *contactDetail = [[ContactDetail alloc] init];
    NSString *fUsername = [[NSString alloc] initWithString:[dicField objectForKey:@"username"]];
    contactDetail.friendUsername = fUsername;
    [fUsername release];
    [self.navigationController pushViewController:contactDetail animated:YES];
    [contactDetail release];
}

#pragma mark -
#pragma mark MKAnnotation delegate

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    MAnnotation *annotation1 = annotation;
    
    MKAnnotationView *annView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"] autorelease];
    annView.canShowCallout = NO;
    annView.calloutOffset = CGPointMake(0, 0);
    
    NSString *st = @"";
    if (annotation1.isRoot)
        st = @"gmap_blue_point.png";
    else
        st = @"gmap_green_point.png";
    
    UIImage *pinImage = [UIImage imageNamed:st];
    annView.image = pinImage;
    return annView;
}

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:overlay] autorelease];
    
    return mapOverlayView;
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    // not rotate
    radarGScanImageView.hidden = YES;
    radarWScanImageView.hidden = YES;
    [timer1 invalidate];
    timer1 = nil;
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    [locationArray removeAllObjects];
    [locationArray addObjectsFromArray:[(NSMutableDictionary *)[responseString JSONValue] objectForKey:@"friendlist"]];
    [responseString release];
    
    [self addOnGoogleMap];
    
    if ([locationArray count] - 1) {
        nextArrowButton.enabled = TRUE;
        backArrowButton.enabled = TRUE;
    }
    
    if ([locationArray count])
    {
        NSDictionary *found = nil;
        for (NSDictionary *mark in locationArray) {
            if ([[mark objectForKey:@"username"] isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]])
                found = mark;
        }
        [locationArray removeObject:found];
        
        [listOfSections addObject:locationArray];
    }
    
    [myTableView reloadData];
    
    radarGScanImageView.hidden = YES;
    radarWScanImageView.hidden = YES;
    [timer1 invalidate];
    timer1 = nil;
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
